import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
// 创建axios的实列
const service = axios.create({
  // 基地址
  baseURL:process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // 超时的时间
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器 -- 加token 
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = store.state.user.token
    if(token){
      // 如果有token就加在请求头上
      config.headers.Authorization = `Bearer ${token}`
    }
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['X-Token'] = getToken()
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器 -- 处理401
service.interceptors.response.use(
  response => {
    // const res = response.data
    if(response.data.success === false){
      return response.data.message
    }else {
      return response.data
    }
  },
  error => {
    if(error.response.data.code === 10002 ){
      //token失效  删除本地登录信息
      store.dispatch('user/userLoginOut')
      // 跳转，重新登录
      router.push('/login?return_url=' + router.currentRoute.path)

    }
    return Promise.reject(error)
  }
)

// 导出
export default service
